﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.LockStep
{
    public interface IReferenceData : IStreamData
    {
        void OnRecycle();
        int ReferenceId { get; set; }
        object ReferenceObj { get; set; }
    }

    /// <summary>
    /// 继承自此类后，不允许有其他其他实例字段，因为底层在一定情况下会和其他实例交换ReferenceObj和ReferenceId。
    /// 自己额外定义的字段会交换不到，导致数据对不上
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ReferenceData<T> : StreamData<ReferenceData<T>>, IReferenceData where T : class
    {
        public int ReferenceId { get; set; }
        public object ReferenceObj { get => Data; set => Data = value as T; }

        public T Data { get; set; }

        public ReferenceData()
        {
            ReferenceId = PoolTools.GetNextObjId();
        }

        public abstract void OnRecycle();

        public override ReferenceData<T> ReadFrom(IFrameDataStream stream)
        {
            var newId = stream.ReadInt32();
            PoolTools.PopReference(newId, this);
            return this;
        }

        public override void WriteTo(IFrameDataStream stream)
        {
            stream.WriteInt32(ReferenceId);
        }

        public override void Clear()
        {
            PoolTools.PushReference(this);
        }
    }
}